
import os
import time
import pandas as pd
import spire.doc
from docx import Document,shared

from docx.oxml.ns import qn
from docx.enum.text import WD_ALIGN_PARAGRAPH #设置对象居中、对齐等。
from docx.enum.text import WD_TAB_ALIGNMENT,WD_TAB_LEADER #设置制表符等
from docx.enum.text import WD_UNDERLINE
from docx.enum.text import WD_TAB_ALIGNMENT
from docx.enum.table import WD_ALIGN_VERTICAL
from docx.enum.table import WD_ROW_HEIGHT_RULE
from docx.enum.text import WD_LINE_SPACING
from docx.shared import Inches #设置图像大小

from PyPDF2 import PdfReader
from PyPDF2 import PdfWriter

# 自定义包
import config
import utils 
import docwriter
import spec
# 写入Information
def coa_add_information(doc,info_df):
    docwriter.docx_add_heading(doc,u'Information')
    docwriter.docx_add_table(doc,info_df,title=False)

# 写入每批测试项目

def coa_add_specification(doc,df):
    
    docwriter.docx_add_heading(doc,u'Each batch analyzed for below items')
    df.columns = ['Item','Specification','Test Result','Method']
    docwriter.docx_add_table(doc,df,(5.8,4.6,3,4.6))
    
# 模板后的底栏
def coa_add_line(doc):
    doc.add_paragraph(
            "\t\t"
        ).paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    header_para = doc.paragraphs[-1]
    # style1:与页边距齐平
    #header_para.paragraph_format.left_indent = 0
    #header_para.paragraph_format.right_indent = 0
    # #style2:横穿整个页面故段落边距紧贴页边
    header_para.paragraph_format.left_indent = - doc.sections[0].left_margin
    header_para.paragraph_format.right_indent = - doc.sections[0].right_margin
    # 设置制表位分区
    tab_stops = header_para.paragraph_format.tab_stops
    tab_stops.add_tab_stop(shared.Inches(3.5), WD_TAB_ALIGNMENT.LEFT)
    tab_stops.add_tab_stop(shared.Inches(5.5), WD_TAB_ALIGNMENT.RIGHT)
    # 设置横线样式
    header_para.runs[-1].underline = WD_UNDERLINE.SINGLE #厚 DOUBLE双下划线
    #行高为确定值
    header_para.height_rule = WD_ROW_HEIGHT_RULE.EXACTLY
    header_para.height = shared.Pt(0.1)
    #line_space为确定值
    header_para.paragraph_format.line_spacing_rule = WD_LINE_SPACING.EXACTLY 
    header_para.line_spacing = shared.Pt(0.1)

# 签名
def sign(doc,batch = None,sign_date = None):
    sign_par = doc.add_paragraph()
    sign_par.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.LEFT
    run_robin = sign_par.add_run('QC Manager:\t')
    if batch !=None : run_robin.add_picture(config.ROBIN_SIGN,width=Inches(0.7))
    date_par = doc.add_paragraph()
    date_par.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.LEFT
    if sign_date != None :
        date_qc = date_par.add_run(f'Date: {sign_date}')
    else:
        date_qc = date_par.add_run('Date: ')

def add_watermark_docx(filename):
    document = spire.doc.Document()
    document.LoadFromFile(filename)
    textWatermark = spire.doc.TextWatermark()
    textWatermark.Text = "COA TEMPLATE"
    textWatermark.FontSize = 100
    textWatermark.Color = spire.doc.Color.get_Gray()
    textWatermark.FontName = "Arial"
    textWatermark.Layout = spire.doc.WatermarkLayout.Diagonal
    document.Watermark = textWatermark
    document.SaveToFile(filename)
    document.Close()
    
def add_watermark_pdf(filename):
    
    # create a new PdfWriter object
    pdf_writer = PdfWriter()

    # read in the QR code PDF using PdfReader class from PyPDF2 library
    watermark_obj = PdfReader(r'data\template\WaterMark.pdf')
    watermark_page = watermark_obj.pages[0]

    # read in the label PDF using PdfReader class from PyPDF2 library
    file_reader = PdfReader(filename)
    label_page = file_reader.pages[0]

    # merge the QR code page with the label page
    label_page.merge_page(watermark_page)

    # add the merged page to the PdfWriter object
    pdf_writer.add_page(label_page)

    pdf_writer.write(filename)
    
    
error_list=[]       

def bkd_coa_template(df):
    # 创建一个字典，存储产品信息
    productinfo = {"Product Code":df.iloc[0,0],
                "Product Name":df.iloc[0,1],
                'Document type':"COA Template",
                "Doc date":time.strftime("%b %Y", time.localtime())}
    
    # 创建一个文档，用于存储头部信息
    header_template = utils.generate_Header(productinfo)
    doc = Document(header_template)

    # 创建一个字典，存储COA信息
    coa_info = {"Product":productinfo["Product Name"],
                "Product Code":productinfo["Product Code"],
                "Shelf Life":'24 months',
                "Batch #":productinfo["Product Code"][:2]+"YYMMDDNN",
                "Manufacture Date":"20YY-MM-DD"}
    
    # 如果字典中包含Shelf Life，则将Shelf Life的值添加到字典中
    if 'Shelf Life' in df['Item'].values:
        df['Target'].astype(str)
        shelf_life = df[df['Item']=='Shelf Life']['Target'].values[0]
        coa_info['Shelf Life'] = shelf_life.split(" ")[0]+" "+shelf_life.split(" ")[1]
    else:
        error_list.append("Missing Shelf Life")
    # 将字典中的Item和Target插入到字典中，并赋值给coa_info_df
    coa_info_df = pd.DataFrame(list(coa_info.items()),columns=["Item","Target"])
    
    # 将coa_info_df中的Type列添加到coa_spec_df中，并将Test Result设置为空值
    coa_spec_df = df.loc[df["Type"]=="Specification",["Item","Target", "Method"]].reset_index(drop=True)
    coa_spec_df.insert(2,"Test Result","")
    #print(coa_spec_df)
    # 将coa_spec_df中的Item和Target插入到coa_add_information函数中，并赋值给coa_add_specification函数中
    coa_add_information(doc,coa_info_df)
    
    coa_spec_df = spec.sort_spec_df(coa_spec_df)
    coa_add_specification(doc,coa_spec_df)
    coa_add_line(doc)
    sign(doc)
    
    # 设置保存路径，并将文档保存到指定路径
    save_path = utils.set_save_path(productinfo)
    filename=os.path.join(save_path,os.path.split(header_template)[-1])
    #print(filename)

    # 保存文档
    doc.save(filename)
    # 将文档添加到doc_file_list中
    
    return filename
    #doc_file_list.append(filename)

def write_coa_template(productcode,transfer2pdf = False):
    #验证产品信息
    df_p = utils.validate_product_info()
    #将df_p中的Product Code等于productcode的值更新到df_p
    df_p = df_p[df_p["Product Code"] == productcode]
    #重置索引
    df_p = df_p.reset_index(drop=True)
    filename = bkd_coa_template(df_p)
    if transfer2pdf:
        filename = utils.conver2pdf(filename)
        add_watermark_pdf(filename)
    else:    
        add_watermark_docx(filename)
        # 删除Spire.Doc的首行水印
        doc = Document(filename)
        doc.paragraphs[0]._element.getparent().remove(doc.paragraphs[0]._element)
        doc.save(filename)

    #返回文件名
    return filename



if  __name__=="__main__":
    
    df_raw = utils.validate_product_info()
    productcode = "NT1340"
    filename = write_coa_template(productcode,False)
    print(filename)
    
    